

package com.zy.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zy.entity.Branch;
import com.zy.entity.Staff;
import com.zy.mapper.StaffMapper;
import com.zy.service.StaffService;

import java.util.UUID;
import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Sha512Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.Cookie;
import org.springframework.stereotype.Service;

@Service
public class StaffServiceImpl implements StaffService {
    @Resource
    StaffMapper staffMapper;

    public StaffServiceImpl() {
    }

    @Override
    public Staff getById(Integer id) {
        return (Staff) this.staffMapper.selectByPrimaryKey(id);
    }

    @Override
    public void save(Staff staff) {
        String salf = UUID.randomUUID().toString();
        staff.setSfPassword((new Sha512Hash(staff.getSfPassword(), salf, 1024)).toString());
        staff.setSfSalf(salf);
        this.staffMapper.insert(staff);
    }

    @Override
    public void updateById(Staff staff) {
        this.staffMapper.updateByPrimaryKey(staff);
    }

    @Override
    public void delete(Integer id) {
        this.staffMapper.deleteByPrimaryKey(id);
    }

    @Override
    public PageInfo<Staff> page(Staff staff, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        return new PageInfo(this.staffMapper.page(staff));
    }

    @Override
    public Integer login(Staff staff) {
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(staff.getSfUser(), staff.getSfPassword()));
        } catch (AuthenticationException var4) {
            return 0;
        }
        Session session = subject.getSession();
        session.setAttribute("userInfo", subject.getPrincipal());
//        System.out.println(subject.isPermitted("/branch/page"));
        return 1;
    }

    @Override
    public void status(Integer id) {
        Staff staff = staffMapper.selectByPrimaryKey(id);
        staff.setSfStatus(staff.getSfStatus() == 0 ? 1 : 0);
        this.staffMapper.updateByPrimaryKey(staff);
    }

    @Override
    public int logout() {
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.logout();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }
}
